import React, {
  useEffect,
  useRef,
} from 'react'
import { useInViewport } from '../../hooks/use-in-viewport'

type Props = {
  onActive: () => void;
  height?: string;
  width?: string;
}

export const LazyDetector: React.FC<Props> = ({
  onActive,
  height,
  width,
}) => {
  const ref = useRef<HTMLDivElement>(null)
  const [inViewport] = useInViewport(ref, {
    // 完全进入视口
    threshold: 1.0,
  })

  useEffect(() => {
    if (inViewport) {
      onActive()
    }
  }, [inViewport])

  return <div style={{ height, width, background: '#f5f5f5' }} ref={ref} />
}
